package parser

import (
	"strings"

	"gitee.com/u-language/u-language/ucom/ast"
	"gitee.com/u-language/u-language/ucom/ast2"
	"gitee.com/u-language/u-language/ucom/check3"
	"gitee.com/u-language/u-language/ucom/errcode"
	"gitee.com/u-language/u-language/ucom/lex"
	"gitee.com/u-language/u-language/ucom/lex2"
)

// ParserStr 从已经去除换行符的字符串创建ast树
//   - str是已经去除换行符的字符串
func ParserStr(str []string, errctx ...*errcode.ErrCtx) *ast.Tree {
	if len(str) == 0 {
		return nil
	}
	var ctx *errcode.ErrCtx
	if len(errctx) == 0 {
		ctx = errcode.DefaultErrCtx
	} else {
		ctx = errctx[0]
	}
	return ast.NewTree(lex.Lex("1.txt", str, ctx, false), ctx, ast.NewSbt(false), nil)
}

// ParserStr2 创建ast树
//   - str是已经去除换行符的字符串
func ParserStr2(str []string, optin ...func(o *output)) *ast2.Tree {
	if len(str) == 0 {
		return nil
	}
	var outputv = output{
		errctx: errcode.DefaultErrCtx,
	}
	for _, f := range optin {
		f(&outputv)
	}
	var Allstr strings.Builder
	for _, s := range str {
		Allstr.WriteString(s)
		if outputv.noLF {
			continue
		}
		Allstr.WriteString("\n")
	}
	ft := lex2.NewFileToken("1.txt", strings.NewReader(Allstr.String()), outputv.errctx, false)
	tree := ast2.NewTree(ft, "1.txt", outputv.errctx, false)
	if outputv.check {
		check3.CheckTree(tree)
	}
	return tree
}

type output struct {
	errctx *errcode.ErrCtx
	noLF   bool
	check  bool
}

func WithErrCtx(errctx *errcode.ErrCtx) func(o *output) {
	return func(o *output) {
		o.errctx = errctx
	}
}

func WithnoLF(noLF bool) func(o *output) {
	return func(o *output) {
		o.noLF = noLF
	}
}

func WithCheck(check bool) func(o *output) {
	return func(o *output) {
		o.check = check
	}
}
